$(document).ready(function () {
    // 显示教师列表
    function loadteachers() {
        $.ajax({
            url: "/api/teacher/list",
            method: "GET",
            dataType: "json",
            success: function (data) {
                let html = "";
                data.forEach(function (teacher) {
                    html += "<tr data-id='" + teacher.id + "'>";
                    html += "<td>" + teacher.id + "</td>";
                    html += "<td>" + teacher.name + "</td>";
                    html += "<td>" + (teacher.sex === 1 ? '男' : '女') + "</td>";
                    html += "<td>" + teacher.age + "</td>";
                    html += "<td>" + teacher.tno + "</td>";
                    html += "<td>";
                    html += "<button class='layui-btn layui-btn-xs layui-btn-warm editBtn'>编辑</button>";
                    html += "<button class='layui-btn layui-btn-xs layui-btn-danger deleteBtn'>删除</button>";
                    html += "</td>";
                    html += "</tr>";
                });
                $("#teacherList").html(html);
            }
        });
    }

    loadteachers();  // 页面加载时显示教师列表

    $("#addteacherBtn").on("click", function () {
        $("#teacherId").val("");
        $("#teacherName").val("");
        $("#teacherSex").val("1");
        $("#teacherAge").val("");
        $("#teachertno").val("");
        layui.layer.open({
            type: 1,
            title: '添加教师',
            content: $("#teacherFormModal"),
            area: ['500px', '500px'],
            shadeClose: true
        });
    });
    // 处理查询按钮点击事件
    $("#searchBtn").on("click", function () {
        var name = $("#searchName").val().trim();
        if (name === "") {
            alert("请输入教师姓名！");
            return;
        }

        // 使用输入的姓名进行查询
        $.ajax({
            url: "/api/teacher/search",
            method: "GET",
            data: { name: name },  // 将输入的姓名作为查询参数传递
            dataType: "json"
        }).done(function (data) {
            console.log(data);
            let html = "";
            if (data && data.length > 0) {
                data.forEach(function (element) {
                    html += "<tr>";
                    html += "<td>" + element.id + "</td>";
                    html += "<td>" + element.name + "</td>";
                    html += "<td>" + (element.sex === 1 ? "男" : (element.sex === 2 ? "女" : "未知")) + "</td>";
                    html += "<td>" + element.age + "</td>";
                    html += "<td>" + element.tno + "</td>";
                    html += "</tr>";
                });
                $("#searchResult").show();  // 显示查询结果
            } else {
                html = "<tr><td colspan='5'>查无此人</td></tr>";
                $("#searchResult").show();  // 显示查询结果
            }
            $("#teacherSearchResult").html(html);
        }).fail(function () {
            alert("查询失败，请稍后再试！");   // 处理查询失败结果
        });
    });
    // 保存教师（添加或编辑）
    $("#saveteacherBtn").on("click", function () {
        const teacherData = {
            id: $("#teacherId").val(),
            name: $("#teacherName").val(),
            sex: $("#teacherSex").val(),
            age: $("#teacherAge").val(),
            tno: $("#teachertno").val()
        };

        const url = teacherData.id ? "/api/teacher/update" : "/api/teacher/add";
        const method = teacherData.id ? "PUT" : "POST";

        $.ajax({
            url: url,
            method: method,
            contentType: "application/json",
            data: JSON.stringify(teacherData),
            success: function (response) {
                layui.layer.closeAll();
                loadteachers();
                layui.layer.msg("操作成功");
            },
            error: function () {
                layui.layer.msg("操作失败");
            }
        });
    });

    // 取消操作
    $("#cancelBtn").on("click", function () {
        layui.layer.closeAll();
    });

    // 编辑教师
    $(document).on("click", ".editBtn", function () {
        const teacherId = $(this).closest("tr").data("id");

        $.ajax({
            url: "/api/teacher/" + teacherId,
            method: "GET",
            dataType: "json",
            success: function (teacher) {
                console.log(teacher); // 检查数据结构
                $("#teacherId").val(teacher.id || "");
                $("#teacherName").val(teacher.name || "");
                $("#teacherSex").val(teacher.sex || "1");
                $("#teacherAge").val(teacher.age || "");
                $("#teachertno").val(teacher.tno || "");
                layui.layer.open({
                    type: 1,
                    title: '编辑教师',
                    content: $("#teacherFormModal"),
                    area: ['500px', '400px'],
                    shadeClose: true
                });
            },
            error: function () {
                layui.layer.msg("无法获取教师信息，请稍后再试！");
            }
        });
    });


    // 删除教师
    $(document).on("click", ".deleteBtn", function () {
        const teacherId = $(this).closest("tr").data("id");

        layui.layer.confirm('确认删除该教师吗?', {
            btn: ['确认', '取消']
        }, function () {
            $.ajax({
                url: "/api/teacher/delete/" + teacherId,
                method: "DELETE",
                success: function () {
                    loadteachers();
                    layui.layer.msg("删除成功");
                },
                error: function () {
                    layui.layer.msg("删除失败");
                }
            });
        });
    });
});